//
//  RHNetworkConfigVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/8/1.
//

#import "RHNetworkConfigVC.h"
#import "RHNavigationController.h"
#import "CDZQRScanViewController.h"
#import "RHNetworkConfigInfoVC.h"
#import "RHShowProductView.h"
#import "RHAddDeviceController.h"
#import "RHNetDevInfoModel.h"
#import "RHNetworkHelpVC.h"
#import "NetworkConfig.h"

#import <SystemConfiguration/CaptiveNetwork.h>
#import "DevSocketManage.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <NetworkExtension/NetworkExtension.h>

#if TARGET_IPHONE_SIMULATOR
#else
#import <NetworkExtension/NEHotspotConfigurationManager.h>
#endif

#define ap_ip @"10.10.10.1"
//#define ap_ip @"192.168.101.87"
#define ap_port 8080

@interface RHNetworkConfigVC ()
@property (nonatomic ,strong) QMUITextField *ssidInputV;

@property (nonatomic ,strong) QMUITextField *passwordInputV;

@property (nonatomic ,strong) UIImageView *stepImg;

@property (nonatomic ,strong) QMUIButton *remeberBtn;

@property (nonatomic ,strong) QMUITextField *secretTextField;

@property (nonatomic ,copy) NSString *deviceId;//如果点击的是自己名下的设备,传设备id过去获取设备秘钥

@property (nonatomic, copy) void (^connectSocketBlock)(void);//连接socket成功之后
@end

@implementation RHNetworkConfigVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"配网".rh_localized;
    [self setupUI];
    [DevSocketManage shareSocketManage].delegate = self;
    [self showTips];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}




-(void)setupUI{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(appBecomActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"network_help"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(networdConfigGuide)];
    self.navigationItem.rightBarButtonItem = rightItem;
    kWeakSelf;
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.backgroundColor = CFTabViewBgColor;
    [self.view addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    UIView *contentView = kView;
    contentView.backgroundColor = CFTabViewBgColor;
    [scrollView addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        make.width.offset(kUI_WINDOW_W);
    }];
    
    
    UIImageView *connectStateImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ble_connected"]];
    connectStateImg.contentMode = UIViewContentModeScaleAspectFit;
    [contentView addSubview:connectStateImg];
    [connectStateImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(30);
        make.width.mas_offset(kScaleW(225));
        make.height.mas_offset(kScaleW(113));
        make.centerX.mas_offset(0);
    }];
    
    UIImageView *connectedImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ble_connect_success"]];
    [contentView addSubview:connectedImage];
    [connectedImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.width.height.offset(25);
        make.top.equalTo(connectStateImg.mas_bottom).offset(30);
    }];
    
    QMUILabel *connectedLab = [QMUILabel labelWithText:@"APP已同设备建立通讯链接".rh_localized font:kSYSTEMFONT(15) textColor:kRGB(63, 68, 67)];
    connectedLab.numberOfLines = 0;
    [contentView addSubview:connectedLab];
    
    [connectedLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(connectedImage.mas_bottom).offset(15);
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
    }];
    
    
    QMUILabel *wifiTitle = [[QMUILabel alloc]init];
    wifiTitle.text = @"WiFi";
    wifiTitle.textColor = kRGB(63, 68, 67);
    wifiTitle.font = kSYSTEMFONT(16);
    [contentView addSubview:wifiTitle];
    [wifiTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.equalTo(connectedLab.mas_bottom).offset(30);
    }];
    
    UIView *wifiContentView = kView;
    wifiContentView.layer.cornerRadius = 8;
    wifiContentView.backgroundColor = UIColor.whiteColor;
    [contentView addSubview:wifiContentView];
    [wifiContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(wifiTitle);
        make.right.mas_offset(-15);
        make.top.equalTo(wifiTitle.mas_bottom).offset(5);
    }];
    
    
    QMUILabel *wifiNameLab = [[QMUILabel alloc]init];
    wifiNameLab.text = @"WiFi名称".rh_localized;
    wifiNameLab.textColor = kColorRGBA(63, 68, 67, 0.8);
    wifiNameLab.font = kSYSTEMFONT(14);
    [wifiContentView addSubview:wifiNameLab];
    [wifiNameLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.mas_offset(15);
    }];
    
    
    _ssidInputV = [[QMUITextField alloc] init];
    _ssidInputV.backgroundColor = kRGB(244, 244, 244);
    _ssidInputV.layer.cornerRadius = 8;
    _ssidInputV.placeholder =  @"请输入WiFi名称".rh_localized;
    _ssidInputV.textInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    _ssidInputV.text = [UserDefaults objectForKey:kWiFiSSID]?[UserDefaults objectForKey:kWiFiSSID]:nil;
    _ssidInputV.font = kSYSTEMFONT(14);
    [wifiContentView addSubview:_ssidInputV];
    
    UIView *ssidRightView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    QMUIButton *selectBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [selectBtn setImage:[UIImage imageNamed:@"arrow_2"] forState:UIControlStateNormal];
    [ssidRightView addSubview:selectBtn];
    _ssidInputV.rightView = ssidRightView;
    _ssidInputV.rightViewMode = UITextFieldViewModeAlways;
    [_ssidInputV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(wifiNameLab.mas_bottom).offset(15);
        make.height.mas_equalTo(45);
    }];

    
    
    
    QMUILabel *wifiPwdLab = [[QMUILabel alloc]init];
    wifiPwdLab.text = @"WiFi密码".rh_localized;
    wifiPwdLab.textColor = kColorRGBA(63, 68, 67, 0.8);
    wifiPwdLab.font = kSYSTEMFONT(14);
    [wifiContentView addSubview:wifiPwdLab];
    [wifiPwdLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.equalTo(weakSelf.ssidInputV.mas_bottom).offset(20);
    }];
    _passwordInputV = [[QMUITextField alloc] init];
    _passwordInputV.backgroundColor = kRGB(244, 244, 244);
    _passwordInputV.layer.cornerRadius = 8;
    _passwordInputV.placeholder = @"请输入WiFi密码".rh_localized;
    _passwordInputV.secureTextEntry = YES;
    _passwordInputV.textInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    _passwordInputV.text = [UserDefaults objectForKey:kWiFiPWD];
    _passwordInputV.font = kSYSTEMFONT(14);
    [wifiContentView addSubview:_passwordInputV];
    
    //是否记住wifi名称和密码
    if ([kUserDefaults boolForKey:kIsRememberWiFi]) {
        NSString *ssid = [kUserDefaults objectForKey:kWiFiSSID];
        NSString *pwd  = [kUserDefaults objectForKey:kWiFiPWD];
        self.ssidInputV.text = ssid;
        self.passwordInputV.text = pwd;
    }else{
      
    }
    
    UIView *pwdRightView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    QMUIButton *seeBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [pwdRightView addSubview:seeBtn];
    [seeBtn setImage:[UIImage imageNamed:@"show_pwd"] forState:UIControlStateNormal];
    [seeBtn setImage:[UIImage imageNamed:@"show_pwd_s"] forState:UIControlStateSelected];
    _passwordInputV.rightViewMode = UITextFieldViewModeAlways;
    _passwordInputV.rightView = pwdRightView;
    [_passwordInputV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(wifiPwdLab.mas_bottom).offset(15);
        make.height.mas_equalTo(45);
    }];
    
    QMUIButton *remeberBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [remeberBtn setTitle:@"记住名称和密码".rh_localized forState:UIControlStateNormal];
    [remeberBtn setTitleColor:kRGB(86, 194, 113) forState:UIControlStateNormal];
    [remeberBtn setImage:[UIImage imageNamed:@"remeber_normal"] forState:UIControlStateNormal];
    [remeberBtn setImage:[UIImage imageNamed:@"remeber_selected"] forState:UIControlStateSelected];
    remeberBtn.titleLabel.font = kSYSTEMFONT(12);
    remeberBtn.imagePosition = QMUIButtonImagePositionLeft;
    remeberBtn.spacingBetweenImageAndTitle = 10;
    [wifiContentView addSubview:remeberBtn];
    self.remeberBtn = remeberBtn;
    [remeberBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.passwordInputV.mas_bottom).offset(10);
        make.left.mas_offset(15);
        make.height.mas_offset(25);
        make.bottom.mas_offset(-15);
    }];
    remeberBtn.selected = [kUserDefaults boolForKey:kIsRememberWiFi];
    
    
    QMUILabel *scrTitleLab = [[QMUILabel alloc]init];
    scrTitleLab.text = @"设置密钥".rh_localized;
    scrTitleLab.textColor = kColorRGBA(63, 68, 67, 1);
    scrTitleLab.font = kSYSTEMFONT(16);
    [contentView addSubview:scrTitleLab];
    [scrTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.equalTo(wifiContentView.mas_bottom).offset(20);
    }];
    
    QMUIButton *helpBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [contentView addSubview:helpBtn];
    [helpBtn setImage:[UIImage imageNamed:@"secret_help"] forState:UIControlStateNormal];
    [helpBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(35);
        make.left.equalTo(scrTitleLab.mas_right).offset(0);
        make.centerY.equalTo(scrTitleLab);
    }];
    
    _secretTextField = [[QMUITextField alloc] init];
    _secretTextField.backgroundColor = UIColor.whiteColor;
    _secretTextField.layer.cornerRadius = 8;
    _secretTextField.placeholder = @"请输入设备密钥".rh_localized;
    _secretTextField.textInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    _secretTextField.font = kSYSTEMFONT(14);
    [contentView addSubview:_secretTextField];
    
    
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 35)];
    QMUIButton *scanBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [rightView addSubview:scanBtn];
    [scanBtn setImage:[UIImage imageNamed:@"input_scan_icon"] forState:UIControlStateNormal];
    _secretTextField.rightViewMode = UITextFieldViewModeAlways;
    _secretTextField.rightView = rightView;
    [_secretTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(scrTitleLab.mas_bottom).offset(15);
        make.height.mas_equalTo(45);
    }];
    
    
    QMUIButton *seeSecretBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [contentView addSubview:seeSecretBtn];
    [seeSecretBtn setTitle:@"查看设备密钥>>>".rh_localized forState:UIControlStateNormal];
    [seeSecretBtn setTitleColor:kColorRGBA(63, 68, 67, 0.8) forState:UIControlStateNormal];
    seeSecretBtn.titleLabel.font = kSYSTEMFONT(12);
    seeSecretBtn.hidden = YES;
    [seeSecretBtn mas_makeConstraints:^(MASConstraintMaker *make) {
      
        make.left.equalTo(weakSelf.secretTextField).offset(0);
        make.top.equalTo(weakSelf.secretTextField.mas_bottom).offset(10);
    }];
    
    QMUIButton *btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(0, 0, 204, 45)];
    [btn setBackgroundColor:UIColor.blackColor];
    [btn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [btn setTitle:@"确认".rh_localized forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [btn.layer setCornerRadius:8];
    [btn setGradientBackgroundWithColors:@[kRGB(106, 215, 133),kRGB(94, 203, 183)] locations:@[@(0),@(1)] startPoint:CGPointMake(0, 0.5) endPoint:CGPointMake(1, 0.5)];
    [contentView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(25);
        make.right.mas_offset(-25);
        make.top.equalTo(seeSecretBtn.mas_bottom).offset(30);
        make.height.mas_equalTo(50);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-20);
    }];


    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf sendSsidAndPassword];
    }];
    
    selectBtn.hidden = YES;
    [[selectBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf.view endEditing:YES];
//        [weakSelf getConfigWifiList];
//        PEChoiceWiFiView *wifiView = [[PEChoiceWiFiView alloc]init];
//        wifiView.curSsid = [weakSelf getSSID];
//        wifiView.wifiList = @[[weakSelf getSSID]];
//        if (wifiView.curSsid.length>0) {
//            wifiView.wifiList = @[[weakSelf getSSID]];
//        }
//
//        wifiView.choiceResultBlock = ^(NSString * _Nonnull ssid) {
//            weakSelf.ssidInputV.text = ssid;
//        };
//        [wifiView showAnimation];
    }];
    
    [[seeBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        x.selected = !x.selected;
        weakSelf.passwordInputV.secureTextEntry = !x.selected;
    }];
    
    [[remeberBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        x.selected = !x.selected;
    }];
    
    [[helpBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf showTipsViewWithContent:@"设备密钥是每台设备对应的入网凭证，在我的设备列表中-设备信息，可以找到设备密钥。设备密钥为机密信息，请妥善保存。".rh_localized];
    }];
    
    [[scanBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf scanQRC];
    }];
}


-(void)networdConfigGuide
{
    [self.navigationController pushViewController:[RHNetworkHelpVC new] animated:YES];
}
-(void)showTips
{
    QMUIAlertController *alertVC = [QMUIAlertController alertControllerWithTitle:nil message:@"请先连接设备热点,再进行配网!" preferredStyle:QMUIAlertControllerStyleAlert];
    QMUIAlertAction *sure = [QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        [self checkIsWIFI];
    }];
    [alertVC addAction:sure];
    [alertVC showWithAnimated:YES];
}


#pragma mark ----- 发送WIFI名称和密码 设备密钥  区域 品牌
-(void)sendSsidAndPassword
{
    
    
    if(_ssidInputV.text.length == 0){
        [QMUITips showError:@"请输入WiFi名称".rh_localized];
        return;
    }
    if (_passwordInputV.text.length == 0) {
        [QMUITips showError:@"请输入WiFi密码".rh_localized];
        return;
    }
    if (_secretTextField.text.length == 0) {
        [QMUITips showError:@"请输入设备密钥".rh_localized];
        return;
    }
    
    if([DevSocketManage shareSocketManage].socketState != DevSocketStateConnected){
        [QMUITips showLoading:@"连接socket".rh_localized inView:kAppWindow];
        [self connectDeviceSocket];
        kWeakSelf;
        self.connectSocketBlock = ^{
            [weakSelf sendSsidAndPassword];
        };
        return;
    }
    
    //校验密钥
    NSString *deviceId = @"";
    if (deviceId.length > 0) {
        [QMUITips showLoadingInView:self.view];
        [BaseModel startWithCompletionAPIKey:H_vetifyDevicePassword argument:@{@"deviceId":deviceId,@"password":self.secretTextField.text} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if (resultModel.code == 200) {
                [self sendComandToDevice];
                [self updateRemeberWiFiInfoStatus];
            }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
    }else{
        [self sendComandToDevice];
        [self updateRemeberWiFiInfoStatus];
    }

}

-(void)sendComandToDevice
{
    NSDictionary *dic = @{
        @"type": @"ConfigNet",
        @"protocol_Ver": @"1.0",
        @"Msg":@{
            @"STASSID":ValidNullData(self.ssidInputV.text),
            @"STAPWD":ValidNullData(self.passwordInputV.text),
            @"DEVKEY":ValidNullData(self.secretTextField.text),
            @"COUNCODE":ValidNullData([kUserDefaults objectForKey:kRegionCode]),
            @"BRANDID":ValidNullData([NetworkConfig sharedConfig].brandID)//brandId  当前登录的品牌
        }
    };
    NSString *contentString = [dic yy_modelToJSONString];
    [QMUITips showLoading:@"" inView:kAppWindow];
    [[DevSocketManage shareSocketManage]sendMessage:contentString];
    [self performSelector:@selector(timeoutAction) withObject:nil afterDelay:3];
}

-(void)timeoutAction
{
    [QMUITips hideAllTips];
    [QMUITips showInfo:@"响应超时".rh_localized];
}

-(void)updateRemeberWiFiInfoStatus
{
    //记住wifi名称和密码
    [kUserDefaults setBool:self.remeberBtn.selected forKey:kIsRememberWiFi];
    if (self.remeberBtn.selected) {
        [kUserDefaults setObject:self.ssidInputV.text forKey:kWiFiSSID];
        [kUserDefaults setObject:self.passwordInputV.text forKey:kWiFiPWD];
    }
}

//app从后台进入前台
-(void)appBecomActive
{
    if([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi){
        //获取WIFI名称
        NSString *ssid = [self getSSID];
        NSLog(@"----->当前WIFI名称:%@",ssid);
        //连接端口
//        if([DevSocketManage shareSocketManage].socketState == DevSocketStateDisconnect)
//        {
//            [QMUITips showLoading:@"连接socket".rh_localized inView:kAppWindow];
//            [self connectDeviceSocket];
//        }
        
    }
}

#pragma mark ------  判断当前是否连接WIFI
-(void)checkIsWIFI{

    if([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi){
        //获取WIFI名称
        NSString *ssid = [self getSSID];
       
        NSLog(@"----->当前WIFI名称:%@",ssid);
        //连接端口
        [QMUITips showLoading:@"连接socket".rh_localized inView:kAppWindow];
        [self connectDeviceSocket];
       
        //获取IP地址,测试用
        [self getNetworkAddressDetailHandler:^(NSString *interface, NSString *address, NSString *addressType) {
            NSLog(@"---->%@\n IP:---->%@\n type:---->%@",interface,address,addressType);
           
        }];
       
    }else{
        NSString *urlString = @"App-Prefs:root=WIFI";
        NSURL *url = [NSURL URLWithString:urlString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                    
                }];
            }
        }
    }
}

#pragma mark ------ 获取WIFI名称
-(NSString *)getSSID
{
    NSString *ssid = @"";
    CFArrayRef arrRef = CNCopySupportedInterfaces();
    NSArray *ifs = (__bridge id)arrRef;
    for (NSString *ifnam in ifs) {
        CFDictionaryRef dicRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        NSDictionary *info = (__bridge id)dicRef;
        if (info[@"BSSID"]) {
            ssid = info[@"SSID"];
        }
        if(dicRef !=nil) {
            CFRelease(dicRef);
        }
    }
    if(arrRef != nil) {
        CFRelease(arrRef);
    }
    return ssid;
}
//获取地址结构体对象，并遍历
- (NSString *)getNetworkAddressDetailHandler:(void(^)(NSString *interface, NSString *address, NSString *addressType))handler
{
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    success = getifaddrs(&interfaces);
    if (success == 0) {
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            [self getAddress:temp_addr handler:handler];
            temp_addr = temp_addr->ifa_next;
        }
    }
    freeifaddrs(interfaces);
    return nil;
}
/**
 地址类型释义    temp_addr->ifa_name
 lo     本地回环 (Loopback)
 en     无线网 (WiFi)
 pdp_ip 蜂窝网络 (Cellular)
 awdl   通信Wi-Fi (Apple Wireless Direct Link，用于AirDrop、AirPlay、GameKit 和 Apple Pencil )
 utun   虚拟隧道 (VPN)
 ipsec  虚拟隧道 (VPN)
 llw    低延迟无线局域网（Low-latency WLAN）
 */

//处理单个地址对象
- (void)getAddress:(struct ifaddrs *)temp_addr handler:(void(^)(NSString *interface, NSString *address, NSString *addressType))handler
{
    // 网络地址族
    sa_family_t sa_family = temp_addr->ifa_addr->sa_family;
    // 网络接口
    NSString *interface;
    // 网络地址
    NSString *address;
    // 网络地址
    NSString *addressType;
    // IPv4
    if(sa_family == AF_INET){
        interface = [NSString stringWithUTF8String:temp_addr->ifa_name];
        struct sockaddr_in *ifa_addr = ((struct sockaddr_in *)temp_addr->ifa_addr);
        address = [NSString stringWithUTF8String:inet_ntoa(ifa_addr->sin_addr)];
        addressType = @"IPv4";
    }
    // IPv6
    else if (sa_family == AF_INET6){
        interface = [NSString stringWithUTF8String:temp_addr->ifa_name];
        struct sockaddr_in6 *ifa_addr = ((struct sockaddr_in6 *)temp_addr->ifa_addr);
        char buf[INET6_ADDRSTRLEN] = {0};
        const char *ipv6 = inet_ntop(AF_INET6, &ifa_addr->sin6_addr, buf, sizeof(buf));
        address = [NSString stringWithUTF8String:ipv6];
        addressType = @"IPv6";
    }
    if (interface.length && handler){
        if([address hasPrefix:@"192.168"]){
            handler(interface, address, addressType);
        }
       
    }
}

#pragma mark ------ 连接设备热点

-(void)connectDeviceHotWithDeviceId:(NSString *)deviceId
{
    //TP-LINK B0F3      Zruipower2016!
    //TP-LINK_5G_B0F3   Zruipower2016!
    //Laboratory-5G     lab2303!
    //Laboratory     lab2303!
    //Laboratory-Y5G     lab2303s
    NSString *ssid = @"Laboratory";
    NSString *password = @"lab2303!";
    NSString *currentWIFI = [self getSSID];
    //如果已连接热点
    if([currentWIFI isEqualToString:ssid]){
        
        [self connectDeviceSocket];
    }else{
        [QMUITips showLoading:@"连接设备热点...".rh_localized inView:self.view];
        
        NEHotspotConfiguration * hotspotConfig = [[NEHotspotConfiguration alloc] initWithSSID:ssid passphrase:password isWEP:NO];
        hotspotConfig.joinOnce = YES;
        // 开始连接 (调用此方法后系统会自动弹窗确认)
        [[NEHotspotConfigurationManager sharedManager] applyConfiguration:hotspotConfig completionHandler:^(NSError * _Nullable error) {
            [QMUITips hideAllToastInView:self.view animated:YES];
            if(!error){
                NSLog(@"已连接");
                NSString *currentWIFI = [self getSSID];
                if([currentWIFI isEqualToString:ssid]){
                    
                    //刚连接上设备热点,1秒后再连socket
                    [QMUITips showLoadingInView:self.view];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [QMUITips hideAllToastInView:self.view animated:YES];
                        //连接设备热点成功,连接socket
                        [self connectDeviceSocket];
                    });
                    
                }else{
                    //加入失败,跳转到到系统WIFI设置页面
                    [self jumpToSetWifi];
                }
            
                NSLog(@"---->当前连接的WIFI:%@",[self getSSID]);
//                [[NEHotspotConfigurationManager sharedManager] getConfiguredSSIDsWithCompletionHandler:^(NSArray<NSString *> * array) {
//                        for (NSString * str in array) {
//                            NSLog(@"加入过的WiFi：%@",str);
//
//                        }
//                }];
            }else if (error && error.code != 13 && error.code != 7) {
                NSLog(@"加入失败");
            }else if(error.code ==7){
                NSLog(@"已取消");
            }else{
                NSLog(@"其他原因");
            }
            NSLog(@"---->错误信息:%@",error);
        }];
            
      
        
    }
    
}

//跳转系统WIFI设置页面
- (void)jumpToSetWifi{
    NSString *urlString = @"App-Prefs:root=WIFI";
    NSURL *url = [NSURL URLWithString:urlString];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
//                self.isToSetWifi = YES;
            }];
        }
    }
}


#pragma mark ------ 连接设备socket
-(void)connectDeviceSocket
{
    [[DevSocketManage shareSocketManage]connectToHost:ap_ip onPort:ap_port result:^(BOOL isConnect) {
        if(isConnect){
            NSLog(@"----->连接正常");
            
        }else{
            NSLog(@"----->连接失败");
        }
    }];
}

- (void)DevSocket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    NSLog(@"---->连接 %@ 成功",host);
    [QMUITips hideAllTips];
    [QMUITips showSucceed:@"连接socket成功".rh_localized];
    if(self.connectSocketBlock){
        self.connectSocketBlock();
    }
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        NSDictionary *dic = @{@"type":@"ConfigNet",
//                              @"protocol_Ver":@"1.0",
//                              @"Msg":@"hello"
//        };
//       NSString *content = [dic yy_modelToJSONString];
//       [[DevSocketManage shareSocketManage]sendMessage:content];
//    });
    
}

- (void)DevSocketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    [QMUITips hideAllTips];
    [QMUITips showInfo:@"socket断开".rh_localized];
    self.connectSocketBlock = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)DevSocket:(GCDAsyncSocket *)sock didReceiveData:(NSString *)data withTag:(long)tag
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [QMUITips hideAllTips];
    NSDictionary *dic = [data jsonStringToDictionary];
    NSLog(@"----->收到消息:%@",dic);
    if (dic) {
       
        if([dic[@"type"] isEqualToString:@"ReqConfigNet"]){
            if([dic[@"Msg"] isEqualToString:@"OK"]){
                [QMUITips showSucceed:@"配网成功".rh_localized inView:self.view hideAfterDelay:1];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
               
            }
        }
        
        if([dic[@"type"]isEqualToString:@"ReqConfigNetResend"]){
            [self sendSsidAndPassword];
            [QMUITips hideAllTips];
            [QMUITips showLoading:@"重发" inView:kAppWindow];
            NSLog(@"---->重发");
        }
    }
}



//扫二维码
- (void)scanQRC{
    if ([self isCameraAvailable]) {
        [self isCanVisitPhotoAndCameraAuthorization:^(BOOL isOK,NSString *alerStr) {
            if (isOK) {
                NSLog(@"权限OK");
                kWeakSelf;
                CDZQRScanViewController *controller = [[CDZQRScanViewController alloc] init];
                controller.resultCallBack = ^(NSString *content) {
//                    weakSelf.snTextField.text = content;
                };
                 RHNavigationController *nav = [[RHNavigationController alloc] initWithRootViewController:controller];
                [nav setModalPresentationStyle:UIModalPresentationOverFullScreen];
                [self presentViewController:nav animated:YES completion:^{
                    
                }];
            }else{
                if (alerStr) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:alerStr preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"设置".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                         if (@available(iOS 10.0, *)) {
                             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                             } else {
                             NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                             if ([[UIApplication sharedApplication] canOpenURL:url]) {
                                 [[UIApplication sharedApplication] openURL:url];
                             }
                         }
                    }];
                    
                    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSLog(@"点击了取消按钮");
                    }];
                    [alert addAction:cancel];
                    [alert addAction:conform];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }
        }];
    }

}

// 判断设备是否有摄像头
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
- (void)isCanVisitPhotoAndCameraAuthorization:(void(^)(BOOL isOK,NSString *alerStr))result {
    PHAuthorizationStatus photo_status = [PHPhotoLibrary authorizationStatus];
    AVAuthorizationStatus camera_status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (photo_status == PHAuthorizationStatusAuthorized&&camera_status ==AVAuthorizationStatusAuthorized) {
        result(YES,nil);
        return;
    }
    
    if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied||
        camera_status ==AVAuthorizationStatusDenied || camera_status ==AVAuthorizationStatusRestricted) {
        if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied) {
            result(NO,@"请在系统设置中打开相册使用权限");
        }else{
            result(NO,@"请在系统设置中打开摄像头使用权限");
        }
        return ;
    }
    
    if (camera_status == AVAuthorizationStatusNotDetermined) {
        //点击弹框授权
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(!granted){//不允许
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"未开启相机权限,请到设置中开启");
                    result(NO,nil);
                });
            }else{
                if (photo_status == PHAuthorizationStatusNotDetermined) {
                    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                               // 回调是在子线程的
                               NSLog(@"%@",[NSThread currentThread]);
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (status != PHAuthorizationStatusAuthorized) {
                                         NSLog(@"未开启相册权限,请到设置中开启");
                                         result(NO,nil);
                                   }else{
                                         result(YES,nil);
                                   }
                               });
                     
                           }];
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        result(YES,nil);
                    });
                }

            }
        }];
        return;
    }
    
    if (photo_status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                   // 回调是在子线程的
                   NSLog(@"%@",[NSThread currentThread]);
                   dispatch_async(dispatch_get_main_queue(), ^{
                       if (status != PHAuthorizationStatusAuthorized) {
                             NSLog(@"未开启相册权限,请到设置中开启");
                             result(NO,nil);
                       }else{
                             result(YES,nil);
                       }
                   });
               }];
    }
}


-(void)showTipsViewWithContent:(NSString *)tips
{
    UIView *bgView = kView;
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    UIView *contentView = kView;
    contentView.backgroundColor = UIColor.whiteColor;
    contentView.layer.shadowColor = [UIColor grayColor].CGColor;
    contentView.layer.shadowRadius = 5;
    contentView.layer.shadowOpacity = 0.5;
    contentView.layer.cornerRadius = 8;
    contentView.layer.shadowOffset = CGSizeMake(0, 2);
    [bgView addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(25);
        make.right.mas_offset(-25);
        make.centerY.mas_offset(0);
    }];
    
    QMUILabel *tipsLab = [[QMUILabel alloc]init];
    tipsLab.textColor = kColorRGBA(63, 68, 67, 0.8);
    tipsLab.text = tips;
    tipsLab.font = kSYSTEMFONT(12);
    tipsLab.textAlignment = NSTextAlignmentCenter;
    tipsLab.numberOfLines = 0;
    tipsLab.qmui_lineHeight = 25;
    [contentView addSubview:tipsLab];
    [tipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.mas_offset(15);
    }];
    
    QMUIButton *sureBtn = [[QMUIButton alloc]init];
    [sureBtn setTitle:@"知道了".rh_localized forState:UIControlStateNormal];
    [sureBtn setTitleColor:kRGB(86, 194, 113) forState:UIControlStateNormal];
    sureBtn.titleLabel.font = kSYSTEMFONT(14);
    [contentView addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tipsLab.mas_bottom).offset(20);
        make.centerX.mas_offset(0);
        make.bottom.mas_offset(-15);
    }];
    
    
    kWeakSelf;
    [[sureBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [bgView removeFromSuperview];
    }];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
